package com.diyunapp.xilinapp.myindent;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.ChatRefundBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.me.FillExpressNumbersActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RefundProgressActivity extends StatusBarFragmentActivity {


    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.buyer_icon)
    ImageView buyerIcon;
    @Bind(R.id.buyer_time)
    TextView buyerTime;
    @Bind(R.id.buyer_state)
    TextView buyerState;
    @Bind(R.id.buyer_type)
    TextView buyerType;
    @Bind(R.id.buyer_money)
    TextView buyerMoney;
    @Bind(R.id.buyer_num)
    TextView buyerNum;
    @Bind(R.id.buyer_result)
    TextView buyerResult;
    @Bind(R.id.buyer_info)
    TextView buyerInfo;
    @Bind(R.id.seller_icon)
    ImageView sellerIcon;
    @Bind(R.id.seller_time)
    TextView sellerTime;
    @Bind(R.id.seller_state)
    TextView sellerState;
    @Bind(R.id.seller_type)
    TextView sellerType;
    @Bind(R.id.seller_money)
    TextView sellerMoney;
    @Bind(R.id.seller_num)
    TextView sellerNum;
    @Bind(R.id.seller_result)
    TextView sellerResult;
    @Bind(R.id.seller_info)
    TextView sellerInfo;
    @Bind(R.id.login_tv)
    TextView loginTv;
    @Bind(R.id.bottom)
    RelativeLayout bottom;
    @Bind(R.id.express_info)
    TextView expressInfo;
    @Bind(R.id.express_com_tv)
    TextView express_com_tv;
    @Bind(R.id.rel_buyer1)
    RelativeLayout relBuyer1;
    @Bind(R.id.buyer_icon1)
    ImageView buyerIcon1;
    @Bind(R.id.buyer_time1)
    TextView buyerTime1;
    private LayoutInflater inflater;
    private String return_id;
    private Context context;
    private List<ChatRefundBean.DataBean> info = new ArrayList<>();
    private String Refund_id;
    private String refund_type;
    private Bitmap myHeadPic_bm;
    public int express_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund_progress);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        ButterKnife.bind(this);
        View headView;
        headView = findViewById(R.id.refundpro_menubar_inc);
        super.MenuWidget(headView);
        Refund_id = getIntent().getStringExtra("Refund_id");
        refund_type = getIntent().getStringExtra("refund_type");
        initView();
//        initDiaData();
    }
    private void initView() {
//        http://www.xilingou.com/mobile/index.php?act=goods&op=ship&member_id=70&return_id=11
//        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=ship&member_id=70&return_id=11";
        String url1 = ""+MainActivity.url+"act=goods&op=ship&member_id="
                + MainActivity.myLogin.getMemberid() + "&return_id=" + Refund_id + "";
        String url2 = ""+MainActivity.url+"act=goods&op=shik&member_id="
                + MainActivity.myLogin.getMemberid() + "&refund_id=" + Refund_id + "";
        String url = null;
        if (refund_type == "1" || refund_type.equals("1")) {
            url = url2;
        } else if (refund_type == "2" || refund_type.equals("2")) {
            url = url1;
        }

        Log.i("xiaogalade", "progress==url" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.GET, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bottom.setVisibility(View.VISIBLE);
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");

                            if (result == 200) {

                                JSONObject data = resultObject.optJSONObject("data");
                                Log.i("zhangxiaoxidebug", "data=" + data);
                                int refund_type = data.optInt("refund_type");
                                String refund_amount = data.optString("refund_amount");
                                String goods_num = data.optString("goods_num");
                                String reason_info = data.optString("reason_info");
                                String buyer_message = data.optString("buyer_message");
                                int add_time = data.optInt("add_time");
                                int seller_time = data.optInt("seller_time");
                                String invoice_no = data.optString("invoice_no");
                                 express_no = data.optInt("express_id");
                                initDiaData();
                                String buyer_name=data.optString("buyer_name");
                                String store_name=data.optString("store_name");
//                                buyerTime.setText(buyer_name+"：" + AbDateUtil.getStringByFormat(seller_time*1000,"yyyy-MM-dd hh:mm:ss"));
                                buyerTime.setText(buyer_name+"：" );
//                                sellerTime.setText(store_name +": "+ AbDateUtil.getStringByFormat(add_time*1000,"yyyy-MM-dd hh:mm:ss"));
                                sellerTime.setText(store_name +": ");
                                if (refund_type == 2) {
                                    buyerType.setText("退款类型：退货");
                                    int seller_state = data.optInt("seller_state");
                                    if (seller_state == 1) {
                                        sellerState.setText("退款在审核中");
                                    } else if (seller_state == 2) {
                                        sellerState.setText("卖家同意退货");
                                        bottom.setVisibility(View.VISIBLE);
                                    } else if (seller_state == 3) {
                                        sellerState.setText("卖家不同意退货");
                                    }
                                } else {
                                    buyerType.setText("退款类型：退款");
                                    int seller_state = data.optInt("seller_state");
                                    if (seller_state == 1) {
                                        sellerState.setText("退款在审核中");
                                    } else if (seller_state == 2) {
                                        sellerState.setText("卖家同意退款");
                                    } else if (seller_state == 3) {
                                        sellerState.setText("卖家不同意退款");
                                    }
                                }
                                buyerMoney.setText("退款金额：" + refund_amount);
                                buyerNum.setText("退款数量：" + goods_num);
                                buyerResult.setText("退款原因：" + reason_info);
                                buyerInfo.setText("退款说明：" + buyer_message);

                                if (invoice_no != "null") {
                                    relBuyer1.setVisibility(View.VISIBLE);
                                    expressInfo.setText(   " , " + invoice_no);
                                    bottom.setVisibility(View.GONE);
                                } else {
                                    relBuyer1.setVisibility(View.GONE);
                                }
                                String seller_message = data.optString("seller_message");
                                String store_avatar = data.optString("store_avatar");
                                if (seller_message != "null") {
                                    sellerType.setText("商家备注：" + seller_message);
                                } else {
                                    sellerType.setVisibility(View.GONE);
                                }
                                String buyericon = MainActivity.myLogin.getHeadimge();
                                if (store_avatar != "") {
                                    Picasso.with(context)
                                            .load(store_avatar)
                                            .resize(64, 64)
                                            .centerCrop()
                                            .placeholder(R.drawable.list_default)
                                            .error(R.drawable.list_default)
                                            .into(sellerIcon);
                                } else {
                                    sellerIcon.setImageResource(R.drawable.list_default);
                                }
                                GetPictureTask myPicTask = new GetPictureTask();
                                myPicTask.execute(buyericon);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });
    }
    private void initDiaData() {
        String url=""+MainActivity.url+"act=goods&op=express";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.GET, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
                            if(result==200){
                                JSONArray data=resultObject.optJSONArray("data");
                                for (int i=0;i<data.length();i++){
                                    JSONObject provinceJson = data.getJSONObject(i);
                                    int id = provinceJson.optInt("id");
                                    if(id==express_no){
                                    String name = provinceJson.getString("name");
                                        express_com_tv.setText(name);
                                    }

                                }


                            }

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {


                    }
                });
    }
    @OnClick({R.id.go_back, R.id.login_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back:
                finish();
                break;
            case R.id.login_tv:

                Intent intent = new Intent();
                intent.setClass(RefundProgressActivity.this, FillExpressNumbersActivity.class);
                intent.putExtra("Refund_id", Refund_id);
                startActivityForResult(intent, 1);
                break;
        }
    }
    public void nextAct(Class act){
        Intent intent = new Intent();
        intent.setClass(this, act);
        startActivity(intent);
    }
    private class GetPictureTask extends AsyncTask<String, String, Integer> {
        @Override
        protected Integer doInBackground(String... params) {
            String pictureUrl = params[0];
            URL imgUrl = null;
            try {
                imgUrl = new URL(pictureUrl);
                HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                myHeadPic_bm = BitmapFactory.decodeStream(is);
                is.close();
                return 1;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return 10;
            } catch (IOException e) {
                e.printStackTrace();
                return 11;
            }
        }

        @Override
        protected void onPostExecute(Integer result) {
            switch (result) {
                case 1:
                    buyerIcon.setImageBitmap(myHeadPic_bm);
                    buyerIcon1.setImageBitmap(myHeadPic_bm);
                    break;
                case 10:
                    break;
                case 11:
                    break;
                default:
                    break;
            }
            super.onPostExecute(result);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 1) {
                initView();
            }
        }
        if (requestCode == 1) {
            if (resultCode == 2) {
                initView();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
